param(
	[Parameter(Mandatory=$false)]                             
	[string]$inputFile="inputlist.txt",     # the input file to store vdi,domain and fid list
	[Parameter(Mandatory=$false)]                             
	[switch]$inputFileSaved,               # tell if inputfile has been saved, otherwise will popup text to let user enter VDI list.
	[Parameter(Mandatory=$false)]                             
	[switch]$functionInvoked              # tell if script needs to invoke functions
)
$st=get-date
$this_path = Split-Path -Parent ($MyInvocation.MyCommand.Definition) # get the directory of this running script
$parent_path=(get-item $this_path).Parent.FullName
If( !$functionInvoked ){
	. "$parent_path\functions.ps1" # import functions to powershell from functions.ps1
}
If( $inputFile -notlike "*\*"){
    $inputFile="$this_path\$inputFile"
}
$inputlist=Get-Inputlist $inputFile $inputFileSaved
#-----------------------------------------------JAVA Setting Checking--------------------------------------------------------------
$java_temp_path="$this_path\temp" # used to store each result csv file from end vdi incase the script breaks in the middle of running unexpectedly so that we can check the file and know which ones we have already checked
del "$java_temp_path\*.csv" -Force -ErrorAction Ignore
del "$this_path\*.csv" -Force -ErrorAction Ignore
New-FileOrFolder $java_temp_path -d
$java_prop_file="$this_path\to_be_checked_java_control_panel.txt" ; New-FileOrFolder $java_prop_file
$java_prop_list=(get-content $java_prop_file |select -Unique|?{$_.trim() -ne ""})
# reference for property meaning http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/jcp/properties.html
If( $java_prop_list -eq $null ){
	Do{ # loop above action if the vdi list is empty 
		write-host "Please save to be checked java property as below format in opened txt file each line as it's empty and then press enter to continue in powershell console, please press 'Ctrl+C' if you want to quit:
		deployment.roaming.profile
		deployment.security.level" ; notepad $java_prop_file
		read-host " "
		$java_prop_list = (get-content $java_prop_file |select -Unique|?{$_.trim() -ne ""})
	}While( $java_prop_list -eq $null  )
}
$java_action={
	param($line,$cnt,$ActionParams)
	try{$vdi,$domain,$fid,$env=$line.split(",").trim()}catch{}
	write-host "Processing in $cnt-$vdi for java control panel checking...`n"
	$java_prop_list,$java_temp_path=$ActionParams 
	$java_pros = [ordered]@{"Category/Setting"="$vdi/$fid/$domain"}
	For( $n=0; $n -lt $java_prop_list.count; $n++ ){
		$prop = "Java/"+$java_prop_list[$n]
		$java_pros.Add($prop,$null)
	}
	If( [string]::IsNullOrWhiteSpace($fid) ){
		$java_pros.Set_Item("Category/Setting","$vdi/fid was not provided/$domain")
		$rst= New-Object PSObject -Property $java_pros ; Write-Host -ForegroundColor Red "$cnt-$vdi FID Not Provided" ; return $rst
	}
	If(Test-Connection $vdi -quiet -count 1 -ErrorAction Ignore){ # write-host "Checking if $vdi is online"
		try{test-path "\\$vdi\c$\" -ErrorAction Stop 1>$null
		}catch{
			If($_.exception -like "*Access is denied*"){$java_pros.Set_Item("Category/Setting","$vdi/$fid/$domain Access denied")}
			$rst= New-Object PSObject -Property $java_pros ; Write-Host -ForegroundColor Red "$cnt-$vdi-Access denied" ; return $rst
		}
		$java_deploy_file="\\$vdi\c$\Users\$fid\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"
		If( !(test-path $java_deploy_file -ErrorAction Ignore) ){
			#<-------------------- try to open javacpl.exe
			$jversion=(ls "\\$vdi\C$\Program Files (x86)\Java").name
			$remote_java_cpl_exe="\\$vdi\C$\Program Files (x86)\Java\$jversion\bin\javacpl.exe"
			$local_java_cpl_exe="C:\Program Files (x86)\Java\$jversion\bin\javacpl.exe"
			If( !(test-path $remote_java_cpl_exe -ea 0) ){
				$java_pros.Set_Item("Category/Setting","$vdi/$fid/$domain javacpl.exe not exists")
				$rst= New-Object PSObject -Property $java_pros ; Write-Host -ForegroundColor Red "$cnt-$vdi javacpl.exe file not exists" ; return $rst
			}else{
				# set registry to allow quser status and then open java conteol panel in the fid session
				reg add "\\$vdi\HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v AllowRemoteRPC /t Reg_Dword /d 0x1 /f 1>$null 2>&1
				If( (quser $fid /server:$vdi 2>$null) -and ((gwmi win32_process -ComputerName $vdi|?{$_.processname -imatch 'aaplayer'}) -eq $null) ){ # fid has logged in the vdi and has no aa task running
				    # create taks to trigger the javacpl.exe <----> still need optimize for this part
					SCHTASKS /CREATE /S $vdi /RU $fid /tn open_java_cpl /sc ONCE /st (get-date).tostring("HH:mm") /F `
					/tr "'$local_java_cpl_exe'" 1>$null 2>&1 
					SCHTASKS /S $vdi /Run /TN open_java_cpl 1>$null 2>&1 
					Do{ # check task finish status
					    $task_finish=(SCHTASKS /S $vdi /QUERY /TN open_java_cpl 2>$null) -imatch "Ready"
						sleep 1
					}While( $task_finish -eq $null )
					SCHTASKS /S $vdi /DELETE /TN open_java_cpl /F 1>$null 2>&1 # delete the task 
				}
			}
		}
		If( !(test-path $java_deploy_file -ErrorAction Ignore) ){
			$java_pros.Set_Item("Category/Setting","$vdi/$fid/$domain java deployment properties file not exists")
		    $rst= New-Object PSObject -Property $java_pros ; Write-Host -ForegroundColor Red "$cnt-$vdi deployment properties file not exists" ; return $rst
		}else{
			Function Set-Object($pro_file){ # read .propertuies file and convert to object
				$obj=New-Object object
				$pro_list=(get-content $pro_file)|?{!$_.startswith('#')}
				try{
					foreach($line in $pro_list){
						$line=$line.split("=")
						Add-Member -InputObject $obj -Name $line[0].trim() -Value $line[1].trim() -MemberType NoteProperty
					}
					return $obj
				}catch{
					return $null
				}finally{}
			}
			$found_java_pros = Set-Object $java_deploy_file
		}
		For( $n=0; $n -lt $java_prop_list.count; $n++ ){
			$prop=$java_prop_list[$n]
			$item="Java/"+ $prop
			$java_pros.Set_Item($item,$found_java_pros.$prop)
		}
		$java_pros.Set_Item("Java/Version","JRE "+$found_java_pros.'deployment.javaws.jre.0.product')
	}else{
		$java_pros.Set_Item("Category/Setting","$vdi-invalid name or offline/$fid/$domain")
	}
	$rst= New-Object PSObject -Property $java_pros
	Write-Host -ForegroundColor Yellow "$cnt-$vdi Done check java control panel info--`n"
	$rst|Export-Csv -Path "$java_temp_path\$vdi-javacpl.csv" -UseCulture -NoTypeInformation -Encoding UTF8 -Force -ErrorAction Ignore
	return $rst
}
$java_control_panel_settings = Start-BulkThreads $inputlist $java_action $java_prop_list,$java_temp_path -maxCnt 100|sort "Category/Setting"
Export-Result $java_control_panel_settings "JAVA Control Panel Settings" "$this_path\java.csv" ([math]::Round(((get-date)-$st).totalseconds))
